/* 尚未归还表
*/
function getAllUnreturnedInfo(currentPage) {
    var pageSize = $("#unreturn_tab_pageSize").val() || 10;//每页几条
    currentPage = currentPage || 1; //当前页(不传值就是1)

    $.ajax({
        url: projectName + "/storeController/getAllUnreturnedInfo",
        data: {"currentPage": currentPage, "pageSize": pageSize},
        async: true,
        type: "post",
        success: function (allData) {
            allData = eval(allData);
            let pageInfo = allData["pageInfo"];
            let totalPage = pageInfo["totalPage"]; //总页数
            fillUnreturnedTab(allData);
            unreturnTabPageNav(currentPage, totalPage, pageSize);
        }
    });

    //页面大小
    $("#unreturn_tab_pageSize").change(function () {
        if (pageSize != $("#unreturn_tab_pageSize").val()) {
            pageSize = $("#unreturn_tab_pageSize").val()
            getAllUnreturnedInfo();//查询所有必须的数据
        }
    });

}

//填充表格
function fillUnreturnedTab(allData) {
    let $unreturn_tab_tbody = $("#unreturn_tab_tbody");
    let allGoods = allData["allUnreturnedInfo"]; //获得所有未归还的货物
    $unreturn_tab_tbody.children("tr").remove();
    for (let i = 0; i < allGoods.length; i++) {
        $unreturn_tab_tbody.append(
            "            <tr>\n" +
            "                <td><span>" + allGoods[i].inventoryId + "</span><span class='hidden'>" + allGoods[i].rentalId + "</span></td>\n" +
            "                <td><a class=\"unreturn_tab_filmTitle  \"  href=\"javascript:;\">" + allGoods[i].filmTitle + "</a><span class='hidden'>" + allGoods[i].filmId + "</span><span class='hidden'>" + allGoods[i].rentalDuration + "</span><span class='hidden'>" + allGoods[i].rentalRate + "</span><span class='hidden'>" + allGoods[i].replacementCost + "</span></td>\n" +
            "                <td class='text-center'><a class=\"unreturn_tab_customerId\" href=\"javascript:;\">" + allGoods[i].customerId + "</a></td>\n" +
            "                <td>" + allGoods[i].rentalDate + "</td>\n" +
            "                <td class='text-danger text-center'>" + "未还" + "</td>\n" +
            "                <td class='text-center'><a class=\"unreturn_tab_staffId\"   href=\"javascript:;\">" + allGoods[i].staffId + "</a></td>\n" +
            "                <td class=\"text-center\">\n" +
            "                    <button class=\"btn btn-primary btn-sm \">归还</button>\n" +
            "                </td>\n" +
            "            </tr>"
        );

    }

    //点击顾客id
    $("#unreturn_tab_tbody").on("click", ".unreturn_tab_customerId", function () {


        let customerId = $(this).text(); //获取顾客id
        $.ajax({
            url: projectName + "/userController/getCustomerInfoByCustomerId",
            type: 'post',
            data: {"customerId": customerId},
            success: function (customerInfo) {
                customerInfo = eval(customerInfo);
                let customerName = customerInfo["firstName"] + " " + customerInfo["lastName"];
                $("#modalTitle").text(customerInfo["customerId"]);
                $("#modalBody").empty();
                $("#modalBody").html(
                    "<ul class=\"list-group\">\n" +
                    "<li class=\"list-group-item\"><strong>会员编号：</strong>" + customerInfo["customerId"] + "</li>\n" +
                    "<li class=\"list-group-item\"><strong>姓名：</strong><input type=\"text\" style=\"border: 0px; min-width: 50%;\" value=\"" + customerName + "\"></li>\n" +
                    "<li class=\"list-group-item\"><strong>邮箱：</strong><input type=\"text\" style=\"border: 0px; min-width: 50%; \" value=\"" + customerInfo["email"] + "\"></li>\n" +
                    "<li class=\"list-group-item\"><strong>注册时间：</strong>" + customerInfo["createDate"] + "</li>\n" +
                    "<li class=\"list-group-item\"><strong>注册门店：</strong>" + customerInfo["storeId"] + "</li>\n" +
                    "<li class=\"list-group-item\"><strong>国家：</strong><input type=\"text\" style=\"border: 0px;  min-width: 50%; \" value=\"" + customerInfo["country"] + "\"></li>\n" +
                    "<li class=\"list-group-item\"><strong>州/省：</strong><input type=\"text\" style=\"border: 0px;  min-width: 50%; \" value=\"" + customerInfo["district"] + "\"></li>\n" +
                    "<li class=\"list-group-item\"><strong>城市：</strong><input type=\"text\" style=\"border: 0px;  min-width: 50%; \" value=\"" + customerInfo["city"] + "\"></li>\n" +
                    "<li class=\"list-group-item\"><strong>地址1：</strong><input type=\"text\" style=\"border: 0px;  min-width: 50%; \" value=\"" + customerInfo["address1"] + "\"></li>\n" +
                    "<li class=\"list-group-item\"><strong>地址2：</strong><input type=\"text\" style=\"border: 0px;  min-width: 50%; \" value=\"" + customerInfo["address2"] + "\"></li>\n" +
                    "<li class=\"list-group-item\"><strong>电话：</strong><input type=\"text\" style=\"border: 0px;  min-width: 50%; \" value=\"" + customerInfo["phone"] + "\"></li>\n" +
                    "<li class=\"list-group-item\"><strong>邮编：</strong><input type=\"text\" style=\"border: 0px;  min-width: 50%; \" value=\"" + customerInfo["postalCode"] + "\"></li>\n" +
                    "<li class=\"list-group-item\"><strong>状态：</strong>" + customerInfo["active"] + "</li>\n" +
                    "</ul>"
                );
                $("#myModal").modal();
            }
        });

    });

    //点击员工id
    $("#unreturn_tab_tbody").on("click", ".unreturn_tab_staffId", function () {
        let staffId = $(this).text();
        $.ajax({
            url: projectName + "/userController/getStaffInfoByStaffId",
            type: 'post',
            data: {"staffId": staffId},
            success: function (staffInfo) {
                staffInfo = eval(staffInfo);
                let staffName = staffInfo["firstName"] + " " + staffInfo["lastName"];
                $("#modalTitle").text(staffInfo["staffId"]);
                $("#modalBody").empty();
                $("#modalBody").html(
                    // "<img  src="+projectName+"/assets/imgs/pp1.jpg style=\"height: 150px;\" class=\"img-responsive center-block img-circle\">\n" +
                    "<ul class=\"list-group\">\n" +
                    "<li class=\"list-group-item\"><strong>员工编号：</strong>" + staffInfo["staffId"] + "</li>\n" +
                    "<li class=\"list-group-item\"><strong>用户名：</strong>" + staffInfo["userName"] + "</li>\n" +
                    "<li class=\"list-group-item\"><strong>姓名：</strong>" + staffName + "</li>\n" +
                    "<li class=\"list-group-item\"><strong>所属门店：</strong>" + staffInfo["storeId"] + "</li>\n" +
                    "<li class=\"list-group-item\"><strong>邮箱：</strong>" + staffInfo["email"] + "</li>\n" +
                    "<li class=\"list-group-item\"><strong>电话：</strong>" + staffInfo["phone"] + "</li>\n" +
                    "<li  class=\"list-group-item\"><strong>国家：</strong> " + staffInfo["country"] + "</li>\n" +
                    "<li  class=\"list-group-item\"><strong>省/州：</strong>" + staffInfo["district"] + " </li>\n" +
                    "<li  class=\"list-group-item\"><strong>城市：</strong> " + staffInfo["city"] + "</li>\n" +
                    "<li  class=\"list-group-item\"><strong>地址1：</strong>" + staffInfo["address1"] + " </li>\n" +
                    "<li  class=\"list-group-item\"><strong>地址2：</strong>" + staffInfo["address2"] + " </li>\n" +
                    "<li  class=\"list-group-item\"><strong>邮编：</strong> " + staffInfo["postalCode"] + "</li>\n" +
                    "<li  class=\"list-group-item\"><strong>状态：</strong> " + staffInfo["active"] + "</li>\n" +
                    "</ul>"
                );
                $("#myModal").modal();
            }
        });
    });


    //点击归还按钮
    $("#unreturn_tab_tbody").on("click", "button", function () {

        $("#return_film_modal_warning").attr("hidden", true);
        let thisRowTR = $(this).parent().parent();
        let thisRowTd = $(this).parent().siblings();//当前行所有的<td>,不包括自己
        let filmTitle = $.trim(thisRowTd.eq(1).children("a").text());//影片名称
        let inventoryId = $.trim(thisRowTd.eq(0).children("span").eq(0).text());//库存编号
        let rentalId = $.trim(thisRowTd.eq(0).children("span").eq(1).text());//rental表的id
        let filmId = $.trim(thisRowTd.eq(1).children("span").eq(0).text());//影片id
        let customerId = $.trim(thisRowTd.eq(2).children("a").text());//顾客id
        let staffId = $.trim(thisRowTd.eq(5).children("a").text());//借出的员工id
        let rentalDuration = $.trim(thisRowTd.eq(1).children("span").eq(1).text());//周期retal_duration
        let rentalRate = $.trim(thisRowTd.eq(1).children("span").eq(2).text());//比率rental_rate
        let replacementCost = $.trim(thisRowTd.eq(1).children("span").eq(3).text());//成本replacementCost

        $("#return_time_div").html(
            "<input type=\"text\" id=\"return_time\" readonly class=\"form-control text-center\"\n" +
            "style=\"background-color: #fff;\">"
        );
        let rentalTime = new Date($.trim(thisRowTd.eq(3).text()));
        let rentalTimeObj = {//借出时间对象
            "rentalTimeString": $.trim(thisRowTd.eq(3).text()),
            "year": rentalTime.getFullYear(),
            "month": (rentalTime.getMonth() + 1),
            "day": rentalTime.getDate(),
            "hour": rentalTime.getHours()
        };

        //填充模态框
        let $groupArr = $("#return_film_modalBody .form-group");
        //影片名的input控件
        $groupArr.eq(0).find("input").val(filmTitle);
        //顾客id的input控件
        $groupArr.eq(1).find("input").val(customerId);
        //出借员工id的input控件
        $groupArr.eq(2).find("input").val(staffId);
        //借出时间的input控件
        $groupArr.eq(3).find("input").val(rentalTimeObj["rentalTimeString"]);

        //填充 周期/比率/成本 input
        $groupArr.eq(4).find("input").eq(0).val(rentalDuration);
        $groupArr.eq(4).find("input").eq(1).val(rentalRate);
        $groupArr.eq(4).find("input").eq(2).val(replacementCost);

        //应付款的2个input,0是整数部分  1是小数部分,
        let $shouldDollar = $groupArr.eq(6).find("input").eq(0);
        let $shouldPanny = $groupArr.eq(6).find("input").eq(1);

        let presentTime = new Date();//当前时间
        //相隔多少天
        let days = (presentTime.getTime() - rentalTime.getTime());
        //应付款的2个input
        let shouldPay = due(days, rentalDuration, rentalRate);
        $shouldDollar.val(shouldPay.toString().split(".")[0]);
        $shouldPanny.val(shouldPay.toString().split(".")[1]);

        //实际付款的2个input初始化
        $groupArr.eq(7).find("input").eq(0).val("");
        $groupArr.eq(7).find("input").eq(1).val("");

        //归还时间
        let returnTime = new Date();

        //执行一个laydate实例
        laydate.render({
            elem: "#return_time", //指定元素
            value: presentTime,
            min: rentalTime.getTime(),
            max: presentTime.getTime(),
            type: "datetime",
            btns: ["now", "confirm"],
            theme: 'molv',
            calendar: true,
            done: function (date) {
                returnTime = new Date(date)
                //相隔多少天
                let days = (returnTime.getTime() - rentalTime.getTime());
                let shouldPay = due(days, rentalDuration, rentalRate);
                $shouldDollar.val(shouldPay.toString().split(".")[0]);
                $shouldPanny.val(shouldPay.toString().split(".")[1]);
            }
        });

        //弹出模态框
        $("#return_film_modal").modal({keyboard: false, backdrop: false});

        //同上按钮
        $groupArr.eq(7).find("a").eq(0).click(function () {
            //实际付款的了2个input元素
            $groupArr.eq(7).find("input").eq(0).val($shouldDollar.val());
            $groupArr.eq(7).find("input").eq(1).val($shouldPanny.val());
        });

        //模态框提交按钮
        $("#return_film_modal_submit").off("click").on("click", function () {
                //查看输入是否合法
                //实际付款的了2个input元素
                let $actualPayInput1 = $groupArr.eq(7).find("input").eq(0);
                let $actualPayInput2 = $groupArr.eq(7).find("input").eq(1);
                let checkREG = /[0-9]+/;
                if (checkREG.test($actualPayInput2.val()) && checkREG.test($actualPayInput1.val())) {
                    //实际付款保留2位小数
                    let amount = Number.parseFloat($actualPayInput1.val() + "." + $actualPayInput2.val()).toFixed(2);
                    $.ajax({
                        url: projectName + "/storeController/clearing",
                        type: "POST",
                        //归还员工id和店铺id从session中获取
                        data: {
                            "rentalId": rentalId, "inventoryId": inventoryId, "filmId": filmId,
                            "customerId": customerId, "returnDate": formatDate(returnTime), "amount": amount
                        },
                        success: function (result) {
                            alert(result);
                            $("#return_film_modal").modal("hide");//关闭模态框
                            thisRowTR.remove();
                            $("#return_time").remove()
                        }
                    });
                } else {
                    $("#return_film_modal_warning").removeAttr("hidden");
                    $("#return_film_modal_warning strong").next("span").text("必须输入正确数字");
                }

        });
    });
}

//生成表格页码导航
function unreturnTabPageNav(currentPage, totalPage) {
    let prePage =
        "<li id=\"prePage\">\n" +
        "<a href=\"javascript:;\">\n" +
        "<span>&laquo;</span>\n" +
        "</a>\n" +
        "</li>";
    let nextPage =
        "<li id=\"nextPage\">\n" +
        " <a href=\"javascript:;\">\n" +
        " <span>&raquo;</span>\n" +
        "</a>\n" +
        "</li> ";
    let gotoBtn =
        "<li class=\"dropup\">\n" +
        "<a href=\"javascript:;\" class=\"dropdown-toggle\" data-toggle=\"dropdown\">\n" +
        "GOTO\n" +
        "<span class=\"caret\"></span>\n" +
        "</a>\n" +
        "<ul id=\"gotoMenu\" class=\"dropdown-menu\" style=\"max-height: 250px; overflow-y: scroll;\">\n" +
        "</ul>\n" +
        "</li>";

    let pageList = "";
    let pageNums = [];
    let startNum = currentPage - 5;
    let endNum = currentPage + 4;    //-5和+4让当前选择的页码保持在中间
    if (currentPage - 5 < 1) {
        startNum = 1;
        endNum = (totalPage > 10) ? 10 : totalPage;
    }
    if (currentPage + 4 > totalPage) {
        startNum = (totalPage - 9) > 0 ? totalPage - 9 : 1;
        endNum = totalPage;
    }
    for (let i = startNum; i <= endNum; i++) {
        pageNums.push(i);
    }
    for (let j = 0; j < pageNums.length; j++) {
        if (currentPage == pageNums[j]) {
            pageList += ("<li class=\"active page-list\"><a href=\"javascript:;\">" + pageNums[j] + "</a></li>");
        } else {
            pageList += ("<li class=\" page-list\"><a href=\"javascript:;\">" + pageNums[j] + "</a></li>");
        }
    }

    $("#unreturn_tab_pagination").html(
        prePage +
        pageList +
        nextPage +
        gotoBtn
    );
    //上一页和下一页按钮的可用性
    currentPage == 1 ? $("#unreturn_tab_pagination #prePage").addClass("disabled") : $("#unreturn_tab_pagination #prePage").removeClass("disabled");
    currentPage == totalPage ? $("#unreturn_tab_pagination #nextPage").addClass("disabled") : $("#unreturn_tab_pagination #nextPage").removeClass("disabled");

    //生成goto里面的数据
    for (let i = 1; i <= totalPage; i++) {
        if (i == currentPage) {
            $("#unreturn_tab_pagination  #gotoMenu").append(
                "<li class=\"active goto-list\"><a href=\"javascript:;\">第" + i + "页</a></li>\n"
            );
        } else {
            $("#unreturn_tab_pagination #gotoMenu").append(
                "<li class=\" goto-list\"><a href=\"javascript:;\">第" + i + "页</a></li>\n"
            );
        }
    }
    //goto点击事件
    $("#unreturn_tab_pagination #gotoMenu .goto-list").click(function () {
        let targetPage = parseInt($(this).text().replace(/[^0-9]/gi, ""));
        if (currentPage != targetPage) {
            currentPage = targetPage;
            getAllUnreturnedInfo(currentPage);//查询所有必须的数据

        }
    });

    //点击页码事件
    $("#unreturn_tab_pagination .page-list").click(function () {
        let targetPage = parseInt($(this).text());

        if (targetPage != currentPage) {
            currentPage = targetPage;
            getAllUnreturnedInfo(currentPage);//查询所有必须的数据

        }
    });

    //上一页事件
    $("#unreturn_tab_pagination #prePage").click(function () {
        if (currentPage != 1) {
            currentPage--;
            getAllUnreturnedInfo(currentPage);//查询所有必须的数据

        }
    });
    //下一页事件
    $("#unreturn_tab_pagination #nextPage").click(function () {
        if (currentPage != totalPage) {
            currentPage++;
            getAllUnreturnedInfo(currentPage);//查询所有必须的数据
        }
    });
}

//应付款
//days 相隔天数(毫秒值) duration周期(天)  rate比率
function due(days, duration, rate) {
    //每小时应付多少钱(duration还没转为毫秒值)
    let oneHour = rate / (duration * 24);
    //周期转为毫秒值
    duration = duration * 1000 * 60 * 60 * 24;
    if (days >= duration) {//相隔天数>周期
        let cycle = (days / duration);//几个周期
        let cycleRemainder = (days % duration);//余数(毫秒)
        let money = Math.floor(cycle) * rate + (cycleRemainder / (1000 * 60 * 60)) * oneHour;
        money = money < 0 ? 0 : money;
        return money;
    } else {//相隔天数<周期 按小时算钱
        let money = (days / (1000 * 60 * 60)) * oneHour;
        money = money < 0 ? 0 : money;
        return money;
    }

}

//格式化日期为"yyyy-MM-dd hh:mm:ss"
function formatDate(returnTime) {
    return returnTime.getFullYear() + "-" + returnTime.getMonth() + "-" + returnTime.getDate() + " " + returnTime.getHours() + ":" + returnTime.getMinutes() + ":" + returnTime.getSeconds();
}



